<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-02-12
 * Time: 13:23
 */

namespace Services\Msg\Core\Task;

use Helpers\Di;
use Services\Login\Login;
use Services\Msg\Models\Task;
use Services\Msg\Models\TaskTarget;

class Operator
{

    /**
     * 标记已读
     *
     * @param $ids
     * @throws \Exception
     *
     * create by ck 20190214
     */
    public function read($ids)
    {
        if (is_numeric($ids)) {
            $ids = [$ids];
        }
        $ids = array_filter($ids);
        if (!$ids) {
            throw new \Exception('缺少任务id');
        }
        $result = Di::get()->db->update(
            'XHRemind_TaskTarget',
            ['isRead', 'updateAt', 'updateBy'],
            [1, time(), Login::getId()],
            sprintf(
                'taskId IN (%s) AND targetId = "%d" AND isDel = 0 AND isRead = 0',
                implode(',', $ids),
                Login::getId()
            )
        );
        if (!$result) {
            throw new \Exception('标记失败');
        }
    }

    /**
     * 标记任务失效
     *
     * @param string $module
     * @param string $subModule
     * @param $extraId
     * @param string $operate
     * @return bool
     * @throws \Exception
     *
     * create by ck 20190214
     */
    public function scrap(string $module, string $subModule, $extraId, string $operate = '')
    {
        $task = Task::findFirst([
            'conditions' => 'module = :module: AND subModule = :subModule: AND extraId = :extraId:
                            AND operate = :operate: AND isDel = 0 AND isScrap = 0',
            'bind'       => [
                'module'    => $module,
                'subModule' => $subModule,
                'extraId'   => $extraId,
                'operate'   => $operate
            ],
            'order' => 'id desc'
        ]);
        if (!$task) {
            return true;
        }
        if ($task->isHandle) {
            throw new \Exception('任务已完成');
        }
        $task->isScrap = 1;
        if (!$task->save()) {
            throw new \Exception($task->getError());
        }
        return true;
    }

    /**
     * 所有关联任务失效，无视operate
     *
     * @param string $module
     * @param string $subModule
     * @param $extraId
     * @return bool
     * @throws \Exception
     *
     * create by ck 20190214
     */
    public function scrapAllOperate(string $module, string $subModule, $extraId)
    {
        $tasks = Task::find([
            'conditions' => 'module = :module: AND subModule = :subModule: AND extraId = :extraId:
                            AND isDel = 0 AND isScrap = 0',
            'bind'       => [
                'module'    => $module,
                'subModule' => $subModule,
                'extraId'   => $extraId,
            ],
            'order' => 'id desc'
        ]);
        if (!count($tasks)) {
            return true;
        }
        try {
            Di::get()->db->begin();
            //循环标记，已处理则跳过
            foreach ($tasks as $task) {
                if ($task->isHandle) {
                    continue;
                }
                $task->isScrap = 1;
                if (!$task->save()) {
                    throw new \Exception($task->getError());
                }
            }
            Di::get()->db->commit();
            return true;
        } catch (\Exception $e) {
            Di::get()->db->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 标记完成
     *
     * @param string $module
     * @param string $subModule
     * @param $extraId
     * @param string $operate
     * @return bool
     * @throws \Exception
     *
     * create by ck 20190214
     */
    public function done(string $module, string $subModule, $extraId, string $operate = '')
    {
        $task = Task::findFirst([
            'conditions' => 'module = :module: AND subModule = :subModule: AND extraId = :extraId:
                            AND operate = :operate: AND isDel = 0 AND isScrap = 0',
            'bind'       => [
                'module'    => $module,
                'subModule' => $subModule,
                'extraId'   => $extraId,
                'operate'   => $operate
            ],
            'order' => 'id desc'
        ]);
        if (!$task) {
            throw new \Exception('任务不存在或已废弃');
        }
        if ($task->isHandle) {
            throw new \Exception('任务已完成');
        }
        $task->isHandle  = 1;
        $task->handlerId = Login::getId();
        if (!$task->save()) {
            throw new \Exception($task->getError());
        }
        return true;
    }

    /**
     * 删除个人任务
     *
     * @param array $ids
     * @return bool
     * @throws \Exception
     *
     * create by ck 20190214
     */
    public function del(array $ids)
    {
        if (!$ids) {
            throw new \Exception('缺少任务id');
        }
        if (!TaskTarget::deleteById($ids)) {
            throw new \Exception('删除失败');
        }
        return true;
    }
}
